//
//  HeaderViewController.m
//  reacticons
//
//  Created by Admin on 7/4/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "HeaderViewController.h"
#import "AppDelegate.h"
#import "Utilities.h"
#import "ImageListViewController.h"
#import "DownloadHelper.h"
#import "DatabaseConnection.h"

@implementation HeaderViewController

@synthesize delegate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        

    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    
    //    [recentlyUsedArray release];
    // sCustom initialization
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSMutableArray *recentlyAddedArray=[[DatabaseConnection getRecentlyAddedPhotos] retain];
    
    if (recentlyAddedArray) {
        if (recentlyAddedArray.count>0) {
            recentlyAdded=[[recentlyAddedArray objectAtIndex:0] retain];
        }
    }
    
    [recentlyAddedArray release];
    
    // Do any additional setup after loading the view from its nib.
    NSString *tagThumbnail=[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"TagThumbnail"];
    
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:tagThumbnail]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:tagThumbnail withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    if (recentlyAdded) {
        NSString * fileName = [NSString stringWithFormat:@"%@/%@", tagThumbnail, [recentlyAdded.photoImage lastPathComponent]];
        if ([[NSFileManager defaultManager] fileExistsAtPath:fileName]) {
            recentlyAddedView.image = [UIImage imageWithContentsOfFile:fileName];
        }
        else
        {
            downloadAdded = [[DownloadHelper alloc] init];
            [downloadAdded setMethod:DOWNLOAD_RECENTLY];
            [downloadAdded downloadFile:[recentlyAdded.photoImage lastPathComponent]
                       toFolderWithName:@"TagThumbnail"
                                withURL:[NSURL URLWithString:recentlyAdded.photoImage]
                 andSuccessNotification:@"downloadRecentlyAddedImageNotify"
                    andFailNotification:@"downloadRecentlyAddedImageNotify_fail"];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downloadFinished:) name:@"downloadRecentlyAddedImageNotify" object:nil];
        }
        
        
    }
    
    
    NSMutableArray *recentlyUsedArray=[[DatabaseConnection getRecentlyUsedPhotos] retain];
    
    if (recentlyUsedArray) {
        if (recentlyUsedArray.count>0) {
            recentlyUsed=[[recentlyUsedArray objectAtIndex:0] retain];
        }
    }
    
    [recentlyUsedArray release];
        
    
    if (recentlyUsed) {
        NSString * fileName = [NSString stringWithFormat:@"%@/%@", tagThumbnail, [recentlyUsed.photoImage lastPathComponent]];
        if ([[NSFileManager defaultManager] fileExistsAtPath:fileName]) {
            recentlyUsedView.image = [UIImage imageWithContentsOfFile:fileName];
        }
        else
        {
            DownloadHelper * _downloadUsed = [[DownloadHelper alloc] init];
            [_downloadUsed setMethod:DOWNLOAD_RECENTLY];
            [_downloadUsed downloadFile:[recentlyUsed.photoImage lastPathComponent]
                       toFolderWithName:@"TagThumbnail"
                                withURL:[NSURL URLWithString:recentlyUsed.photoImage]       
                 andSuccessNotification:@"downloadRecentlyUsedImageNotify" andFailNotification:@"downloadRecentlyUsedImageNotify_fail"];
            
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(downloadFinished:)
                                                         name:@"downloadRecentlyUsedImageNotify"
                                                       object:nil];
            
            DBLOG(@"viewWillAppear: viewWillAppear download recentlyUsed");
        }
        
        
    }
    [self.view insertSubview:recentlyAddedView atIndex:0];
    [self.view insertSubview:recentlyUsedView atIndex:0];

}

#pragma mark - Controller
-(void)removeAllItems{
    recentlyUsed=nil;
    recentlyAdded=nil;
    recentlyUsedView.image=nil;
    recentlyAddedView.image=nil;


    

}
-(BOOL)checkUpdate{

//    static NSArray *animationImagesArray1;
//    if (!animationImagesArray1) {
//        animationImagesArray1=[[NSArray arrayWithObjects:
//                                [UIImage imageNamed:@"out0.png"],
//                                [UIImage imageNamed:@"out1.png"],
//                                [UIImage imageNamed:@"out2.png"],
//                                [UIImage imageNamed:@"out3.png"],
//                                [UIImage imageNamed:@"out4.png"],
//                                //                                  [UIImage imageNamed:@"out5.png"],
//                                [UIImage imageNamed:@"out6.png"],
//                                [UIImage imageNamed:@"out8.png"],
//                                [UIImage imageNamed:@"out9.png"],
//                                [UIImage imageNamed:@"out10.png"],
//                                [UIImage imageNamed:@"out11.png"],
//                                [UIImage imageNamed:@"out12.png"],
//                                [UIImage imageNamed:@"out13.png"],
//                                [UIImage imageNamed:@"out14.png"],
//                                [UIImage imageNamed:@"out15.png"],
//                                nil] retain];
//    }
    
    NSString *tagThumbnail=[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"TagThumbnail"];
    
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:tagThumbnail]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:tagThumbnail withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    
    NSMutableArray *recentlyAddedArray=[[DatabaseConnection getRecentlyAddedPhotos] retain];
    Photo *newRecentlyAdded=[[Photo alloc] init];
    if (recentlyAddedArray) {
        if (recentlyAddedArray.count>0) {
            newRecentlyAdded=[[recentlyAddedArray objectAtIndex:0] retain];
        }
    }
    if (![recentlyAdded.photoImage isEqualToString:newRecentlyAdded.photoImage]) {
        recentlyAdded=[newRecentlyAdded retain];
        NSString * fileName = [NSString stringWithFormat:@"%@/%@", tagThumbnail, [recentlyAdded.photoImage lastPathComponent]];
        if ([[NSFileManager defaultManager] fileExistsAtPath:fileName]) {
//            [recentlyAddedView stopAnimating];
            recentlyAddedView.image = [UIImage imageWithContentsOfFile:fileName];
        }
        else
        {

//            recentlyAddedView.animationImages=animationImagesArray1;
//            recentlyAddedView.animationDuration=1.0f;
//            recentlyAddedView.animationRepeatCount=0;
//            [recentlyAddedView startAnimating];
            
            downloadAdded = [[DownloadHelper alloc] init];
            [downloadAdded setMethod:DOWNLOAD_RECENTLY];
            [downloadAdded downloadFile:[recentlyAdded.photoImage lastPathComponent]
                       toFolderWithName:@"TagThumbnail"
                                withURL:[NSURL URLWithString:recentlyAdded.photoImage]
                 andSuccessNotification:@"downloadRecentlyAddedImageNotify"
                    andFailNotification:@"downloadRecentlyAddedImageNotify_fail"];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downloadFinished:) name:@"downloadRecentlyAddedImageNotify" object:nil];
        }
        
    }
    [newRecentlyAdded release];
    [recentlyAddedArray release];

    
    NSMutableArray *recentlyUsedArray=[[DatabaseConnection getRecentlyUsedPhotos] retain];
    Photo *newRecentlyUsed=[[Photo alloc] init];

    if (recentlyUsedArray) {
        if (recentlyUsedArray.count>0) {
            newRecentlyUsed=[[recentlyUsedArray objectAtIndex:0] retain];
            if (![recentlyUsed.photoImage isEqualToString:newRecentlyUsed.photoImage]) {
                
//                recentlyUsedView.animationImages=animationImagesArray1;
//                recentlyUsedView.animationDuration=1.0f;
//                recentlyUsedView.animationRepeatCount=0;
//                [recentlyUsedView startAnimating];
                
                recentlyUsed =[newRecentlyUsed retain];
                
                NSString * fileName = [NSString stringWithFormat:@"%@/%@", tagThumbnail, [recentlyUsed.photoImage lastPathComponent]];
                
                if ([[NSFileManager defaultManager] fileExistsAtPath:fileName]) {
                    [recentlyUsedView stopAnimating];
                    recentlyUsedView.image = [UIImage imageWithContentsOfFile:fileName];
                }
                else
                {
                    DownloadHelper * _downloadUsed = [[DownloadHelper alloc] init];
                    [_downloadUsed setMethod:DOWNLOAD_RECENTLY];
                    [_downloadUsed downloadFile:[recentlyUsed.photoImage lastPathComponent]
                               toFolderWithName:@"TagThumbnail"
                                        withURL:[NSURL URLWithString:recentlyUsed.photoImage]
                         andSuccessNotification:@"downloadRecentlyUsedImageNotify" andFailNotification:@"downloadRecentlyUsedImageNotify_fail"];
                    [[NSNotificationCenter defaultCenter] addObserver:self
                                                             selector:@selector(downloadFinished:)
                                                                 name:@"downloadRecentlyUsedImageNotify"
                                                               object:nil];
                    DBLOG(@"viewWillAppear: viewWillAppear download recentlyUsed");
                }
                
            }
        }
        else{
//            [recentlyUsedView stopAnimating];
            recentlyUsed=nil;
            recentlyUsedView.image=nil;
        }
        
        
    }
    [newRecentlyUsed release];
    [recentlyUsedArray release];
    
    return YES;
    
}



#pragma mark - Buttons On Clicked

- (IBAction)buttonsOnClicked:(id)sender
{
    DBLOG(@"buttonsOnClicked:%@",self.delegate);
    if ([self.delegate respondsToSelector:@selector(clickedHeaderBtn:)]) {
        DBLOG(@"%d",[sender tag]);
        [self.delegate clickedHeaderBtn:sender];
    }
}

- (void)downloadFinished:(NSNotification*)notify
{
    UIImage * image = nil;
     NSString *tagThumbnail=[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"TagThumbnail"];
    if ([notify.name isEqualToString:@"downloadRecentlyAddedImageNotify"]) {
        NSString * fileName = [notify object];
        image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", tagThumbnail, fileName]];
        UIImage * croppedImage = [Utilities cropImage:image withSize:CGSizeMake(316, 236)];
        
        NSData * downloadImageData = UIImagePNGRepresentation(croppedImage);
        NSString * filePath = [NSString stringWithFormat:@"%@/%@", tagThumbnail, fileName];
        
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
        [[NSFileManager defaultManager] createFileAtPath:filePath contents:downloadImageData attributes:nil];
        [recentlyAddedView stopAnimating];
        recentlyAddedView.image = croppedImage;
    }
    else if ([notify.name isEqualToString:@"downloadRecentlyUsedImageNotify"]) {
        NSString * fileName = [notify object];
        image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", tagThumbnail, fileName]];
        UIImage * croppedImage = [Utilities cropImage:image withSize:CGSizeMake(316, 236)];
        
        NSData * downloadImageData = UIImagePNGRepresentation(croppedImage);
        NSString * filePath = [NSString stringWithFormat:@"%@/%@", tagThumbnail, fileName];
        
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
        [[NSFileManager defaultManager] createFileAtPath:filePath contents:downloadImageData attributes:nil];
        [recentlyUsedView stopAnimating];
        recentlyUsedView.image = croppedImage;
    }
    DBLOG(@"HeaderViewController - downloadFinished[xxx]:%@",notify.name);
    [[NSNotificationCenter defaultCenter] removeObserver:self name:notify.name object:nil];
}
- (void)imageViewFailedToLoadImage:(EGOImageView*)imageView error:(NSError*)error{

}

@end
